package com.wkbb.basic.smartschool;

import com.wkbb.common.utils.MD5Util;

import java.util.*;

public class SSSignUtil {

    /**
     * 第三方应用App密钥
     */
    private static final String APP_ID = "675297155505";
    private static final String APP_SECRET = "9bee5bbf4b8d8039e9e7b83d62355414";
//    private static final String APP_ID = "675868155590";
//    private static final String APP_SECRET = "288ee914c9e69c2ae1c7de94748cd4b2";
//    private static final String APP_ID = "839407155911";
//    private static final String APP_SECRET = "23c51927de3e788fbda4a42644ef9c0b";
    /**
     * 开发者码
     */
    private static final String DEV_CODE = "vrjmwBlNwvh9qU7y";
//    private static final String DEV_CODE = "2zTQH9IjP7rmmaNC";
//    private static final String DEV_CODE = "HRzAx3WPhw3RGV3L";

    private static final String SCHOOL = "2";
    private static final String PARTNER = "3";
    private static final String DEVELOPER = "5";

    /**
     * 通过APP_ID,APP_SECRET方式鉴权
     */
    public static void putSignStr(Map<String, String> param, String objId) {
        param.put("openAppID", APP_ID);
//        param.put("devType", PARTNER);
        putSignStr(param, objId, APP_SECRET);
    }

    /**
     * 通过devCode，key，keyId方式鉴权
     */
    public static void putSignStr(Map<String, String> param, String objId, String key, String keyId) {
        param.put("devCode", DEV_CODE);
        param.put("devType", PARTNER);
        param.put("keyId", keyId);
        putSignStr(param, objId, key);
    }

    /**
     * 签名参数sign生成
     *
     * @param param 请求参数
     */
    private static void putSignStr(Map<String, String> param, String objId, String secret) {
        if (param == null) {
            param = new HashMap<>();
        }
        // 加入公共参数
        param.put("objectid", objId);
        param.put("objType", SCHOOL);
        param.put("timestamp", System.currentTimeMillis() / 1000 + "");

        Collection<String> keySet = param.keySet();
        List<String> keyList = new ArrayList<>(keySet);

        //对key键值按字典升序排序
        Collections.sort(keyList);

        StringBuilder stringABuffer = new StringBuilder();
        for (String key : keyList) {
            stringABuffer.append(key).append("=").append(param.get(key)).append("&");
        }
        stringABuffer.append("key=").append(secret);
        String stringA = stringABuffer.toString();

        String sign = MD5Util.MD5Encode(stringA, "utf-8");
        param.put("sign", sign == null ? "" : sign.toUpperCase());
    }

}
